package com.eqxiu.ieditor.api.controller.mall;

import com.eqxiu.ieditor.api.controller.BaseApiController;
import com.eqxiu.ieditor.api.controller.BaseController;
import com.eqxiu.ieditor.api.controller.common.CategoryRes;
import com.eqxiu.ieditor.commons.web.ResultData;
import com.eqxiu.ieditor.dto.CriteriaDTO;
import com.eqxiu.mall.search.api.IMallSearchServiceApi;
import com.eqxiu.mall.search.dto.FiltersDTO;
import com.eqxiu.mall.search.dto.OrdersDTO;
import com.eqxiu.mall.search.dto.UserInfoDTO;
import com.eqxiu.mall.search.enumeration.SearchApiCodeEnum;
import com.google.gson.Gson;
import eqxiu.mall.product.dto.CategoryDTO;
import eqxiu.mall.product.dto.ProductDTO;
import eqxiu.mall.product.service.api.AttributeProductServiceApi;
import eqxiu.mall.product.service.api.CategoryServiceApi;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Tanghao
 * on 2019/9/9.
 */
@RestController
@RequestMapping("/api/wap")
public class WapSearchController extends BaseController implements BaseApiController {
    Logger logger = LoggerFactory.getLogger(WapSearchController.class);

    @Autowired
    private IMallSearchServiceApi mallSearchServiceApi;
    @Autowired
    private CategoryServiceApi categoryServiceApi;
    @Autowired
    private AttributeProductServiceApi attributeProductServiceApi;

    /**
     * @return
     * @description wap商城调用新搜索接口
     * @author tanghao
     * @date 2019年9月10日
     * @modified 修改为属性查询 tanghao
     */
    @PostMapping("/search")
    public ResultData getScenesByCategoryId2(@RequestBody CriteriaDTO dto, HttpServletRequest request) {
        logger.info("wap搜索参数-->{}", new Gson().toJson(dto));
        //返回前端的map信息
        Map extendMap = new HashMap<>(3);
        extendMap.put("keywords", dto.getKeywords());
        String keyWordInput = null == dto.getKeywords() ? "" : dto.getKeywords();
        com.eqxiu.tiny.pagination.PageDTO<ProductDTO> pagelist = com.eqxiu.tiny.pagination.PageDTO.create(null, 0, dto.getPageNo(), dto.getPageSize());
        List<FiltersDTO> filtersDTOList = new ArrayList<>();
        List<OrdersDTO> ordersDTOList = new ArrayList<>();
        //用户条件
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        String ipAddr = this.getIpAddr(request);
        userInfoDTO.setUid(geUserId(request));
        userInfoDTO.setIp(ipAddr);
        //过滤条件
        handleFilter(dto, extendMap, filtersDTOList);
        //排序条件
        handleOrder(dto, ordersDTOList);
        //处理返回条件
        handlAttrExtendMap(dto,extendMap);
        final int pageNo = dto.getPageNo();
        final int pageSize = dto.getPageSize();
        Map<String, Object> resultMap =mallSearchServiceApi.searchByAttr(dto.getSearchCode(), userInfoDTO, keyWordInput, filtersDTOList, ordersDTOList, pageNo, pageSize);
        pagelist = (com.eqxiu.tiny.pagination.PageDTO<ProductDTO>) resultMap.get("pageResutInfo");
        List<HashMap<String, Object>> attrLists = (List<HashMap<String, Object>>) resultMap.get("attrLists");
        return ResultData.result(true).setObj(pagelist).setMap(extendMap).setList(attrLists);
    }

    private void handleOrder(@RequestBody CriteriaDTO dto, List<OrdersDTO> ordersDTOList) {
        String sortBy = dto.getSortBy();
        if (StringUtils.isNotBlank(sortBy)) {
            OrdersDTO ordersDTO2 = new OrdersDTO();
            if ("createTime".equals(sortBy)) {
                ordersDTO2.setField("create_time");
                ordersDTO2.setOrder("desc");
            } else if ("productUsage".equals(sortBy)) {
                ordersDTO2.setField("seven_refer_count2");
                ordersDTO2.setOrder("desc");
            }else if("navigator_sort".equals(sortBy)){
                ordersDTO2.setField("navigator_sort."+dto.getCategory());
                ordersDTO2.setOrder("desc");
            }
            ordersDTOList.add(ordersDTO2);
        }
    }

    private void handleFilter(@RequestBody CriteriaDTO dto, Map extendMap, List<FiltersDTO> filtersDTOList) {
        //分类信息
        FiltersDTO categoryFilterDTO = new FiltersDTO();
        Integer categoryId = dto.getCategory();
        if (categoryId != null) {
            categoryFilterDTO.setField("navigator_ids");
            categoryFilterDTO.setComparator("equals");
            categoryFilterDTO.setValue(String.valueOf(categoryId));
            filtersDTOList.add(categoryFilterDTO);
            dealCategory(dto.getCategory(),extendMap);
        }
        //端类型（1：PC ；2：APP；4全平台 ；6小程序）
        //h5取app,长页易表单互动取全部
        if(dto.getSearchCode().equals(SearchApiCodeEnum.WAP_H5_SEARCH.code())){
            FiltersDTO osTypeFilterDTO = new FiltersDTO();
            osTypeFilterDTO.setValue("2");
            osTypeFilterDTO.setField("os_type");
            osTypeFilterDTO.setComparator("equals");
            filtersDTOList.add(osTypeFilterDTO);
        }

        //价格过滤( 1 付费 0 免费 30 大于29秀点 其他按数值对应 如29 查询秀点为29的数据.)
        final String priceRange = dto.getPriceRange();
        FiltersDTO priceFilterDTO = new FiltersDTO();
        if (StringUtils.isNotBlank(priceRange)) {
            if ("1".equals(priceRange)) {
                priceFilterDTO.setValue("1");
                priceFilterDTO.setField("price");
                priceFilterDTO.setComparator("gte");
                filtersDTOList.add(priceFilterDTO);
            } else if ("30".equals(priceRange)) {
                priceFilterDTO.setValue("30");
                priceFilterDTO.setField("price");
                priceFilterDTO.setComparator("gte");
                filtersDTOList.add(priceFilterDTO);
            } else {
                priceFilterDTO.setValue(priceRange);
                priceFilterDTO.setField("price");
                priceFilterDTO.setComparator("equals");
                filtersDTOList.add(priceFilterDTO);
            }
        }

        //会员免费
        FiltersDTO sourceTypeFilterDTO = new FiltersDTO();
        if (dto.getSourceType() != null) {
            sourceTypeFilterDTO.setField("source_type");
            sourceTypeFilterDTO.setComparator("equals");
            sourceTypeFilterDTO.setValue(dto.getSourceType().toString());
            filtersDTOList.add(sourceTypeFilterDTO);
        }
        //属性信息
        List<Map<String, Object>> attributeLists = dto.getAttributeLists();
        if (attributeLists != null) {
            for (Map<String, Object> attributeMap : attributeLists) {
                FiltersDTO attributeFilterDTO = new FiltersDTO();
                //属性id
                String attributeId = attributeMap.get("attr_pid").toString();
                attributeFilterDTO.setField(attributeId);
                //属性值id
                String attrValues = attributeMap.get("attr_values").toString();
                String[] attrValueIds = attrValues.split(",");
                if (attrValueIds.length == 1) {
                    //单选
                    attributeFilterDTO.setComparator("equals");
                } else {
                    //多选
                    attributeFilterDTO.setComparator("in");
                }
                attributeFilterDTO.setValue(attributeMap.get("attr_values").toString());
                filtersDTOList.add(attributeFilterDTO);
            }
        }
    }


    /**
     * 处理返回前端的分类信息
     *
     * @return
     */
    public void dealCategory(Integer id, Map extendMap) {
        //获取当前查询的分类信息
        CategoryDTO categoryChild = categoryServiceApi.getCategoryByID(id);
        CategoryRes categoryRes = new CategoryRes();
        if (null != categoryChild) {
            if (0 == categoryChild.getParentId()) {
                categoryRes.setId(id);
                categoryRes.setName(categoryChild.getName());
                categoryRes.setLevel(1);
                categoryRes.setParentId(categoryChild.getParentId());
                extendMap.put("categoryInfo", categoryRes);
            } else {
                // 获取上级分类
                CategoryDTO categoryParent = categoryServiceApi.getCategoryByID(categoryChild.getParentId());
                if (null != categoryParent) {
                    categoryRes.setId(id);
                    categoryRes.setName(categoryChild.getName());
                    categoryRes.setLevel(getLevel(categoryChild));
                    categoryRes.setParentId(categoryChild.getParentId());
                    CategoryRes categoryParentRes = new CategoryRes();
                    categoryParentRes.setId(categoryParent.getId());
                    categoryParentRes.setName(categoryParent.getName());
                    categoryParentRes.setLevel(getLevel(categoryParent));
                    categoryParentRes.setParentId(categoryParent.getParentId());
                    categoryParentRes.setChildCategory(categoryRes);
                    extendMap.put("categoryInfo", categoryParentRes);
                }
            }

        }

    }

    public int getLevel(CategoryDTO categoryDTO) {
        if (null != categoryDTO) {
            if (categoryDTO.getParentId().equals(categoryDTO.getTopId())) {
                return 1;
            } else if ("0".equals(categoryDTO.getTopId().toString())) {
                return 2;
            } else {
                String path = categoryDTO.getPath();
                int number = path.length() - path.replace("/", "").length();
                if (number == 2) {
                    return 3;
                } else if (number == 3) {
                    return 4;
                }
            }
        }
        return 0;
    }

    /**
     * 处理返回数据中返回查询属性相关条件
     * @param dto
     * @param extendMap
     */
    private void handlAttrExtendMap(CriteriaDTO dto, Map extendMap) {
        try {
            List<Map<String, Object>> attributeLists = dto.getAttributeLists();
            List<Map<String, Object>> attributeList = new ArrayList<>();
            for (Map<String, Object> attributeMap : attributeLists) {
                Map<String, Object> returnAttributeMap = new HashMap<>(16);
                List<Map<String, Object>> attributeValueList = new ArrayList<>();
                //属性id
                String attributeId = attributeMap.get("attr_pid").toString();
                Map attributeInfo = attributeProductServiceApi.getAttributeInfo(attributeId);
                if (attributeInfo != null) {
                    String attributeName = (String) attributeInfo.get("attributeName");
                    returnAttributeMap.put("attr_pname", attributeName);
                    returnAttributeMap.put("attr_pid", attributeId);
                }
                //属性值id
                String attrValues = attributeMap.get("attr_values").toString();
                String[] attrValueIds = attrValues.split(",");
                for (String attrValueId : attrValueIds) {
                    Map attributeValueInfo = attributeProductServiceApi.getAttributeInfo(attrValueId);
                    Map<String, Object> returnAttributeValueMap = new HashMap<>(16);
                    if (attributeValueInfo != null) {
                        String attributeName = (String) attributeValueInfo.get("attributeName");
                        returnAttributeValueMap.put("attr_pname", attributeName);
                        returnAttributeValueMap.put("attr_pid", attrValueId);
                    }
                    attributeValueList.add(returnAttributeValueMap);
                }
                returnAttributeMap.put("attr_values", attributeValueList);
                attributeList.add(returnAttributeMap);
            }
            extendMap.put("attributeList", attributeList);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }


}
